const express = require('express');
const { expressjwt } = require('express-jwt');
const config = require('./config');

const app = express();
// 导入cors并配置cors中间件
const cors = require('cors');
app.use(cors())

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// JWT 中间件配置
app.use(
    expressjwt({ 
        secret: config.jwtSecretKey,
        algorithms: ['HS256']  // 添加必需的 algorithms 选项
    }).unless({
        path: [/^\/api/]
    })
);

// 导入并使用用户路由模块
const userRouter = require('./router/user');
app.use('/api', userRouter);

// 导入并使用学院路由模块
const collegeRouter = require('./router/college');
app.use('/my/college', collegeRouter);

// 导入并使用学生路由模块
const studentRouter = require('./router/student');
app.use('/my/student', studentRouter);

// 导入并使用宿舍路由模块
const dormitoryRouter = require('./router/dormitorie');
app.use('/my/dormitorie', dormitoryRouter);
// 错误处理中间件
app.use((err, req, res, next) => {
    if (err.name === 'UnauthorizedError') {
        return res.status(401).json({
            code: 401,
            message: '无效的token'
        });
    }
    res.status(500).json({
        code: 500,
        message: '未知错误'
    });
});

app.listen(3000, () => {
    console.log('Server is running on http://127.0.0.1:3000');
});